import request from '@/utils/request'
import { msgSuccess, msgWarning, confirm } from '@/plugins/modal'
import { parseRows } from '@/utils/frame'

/**
 * 公共普通列表混入js，简化文件的代码长度
 * 实例请看system/config的index.vue
 */

type ListPageParams = {
  id?: string // 主键对应字段，在编辑和删除时用到
  name?: string // 名称对应字段，在删除时用到
  module?: string // 模块名称，在删除时用到
  searchForm?: Ref<any> // 搜索表单字段
  listFn?: () => void | string
  searchFn?: () => void
  deleteFn?: (a: object) => void | string
  exportFn?: () => void | string
  cacheFn?: () => void | string
}

export function useListPage(params: ListPageParams) {
  let { id, name, module, searchForm, listFn, searchFn, deleteFn, exportFn, cacheFn } = params || {}
  const idField = ref(id || 'id') // 主键对应字段
  const nameField = ref(name || 'name') // 名称对应字段
  const moduleName = ref(module || '') // 模块名称
  const loading = ref(false)
  const total = ref(0)
  const listData = ref([]) // 列表数据

  const _searchFormDefault = {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: undefined,
    orderBySort: undefined,
    where: {},
    like: {},
    find: {},
    time: {},
    date: {},
    datetime: {}
  }
  if (!searchForm) searchForm = ref({})
  searchForm.value = { ..._searchFormDefault, ...searchForm.value }

  // 获取列表数据，需要通过参数传入方法或者接口地址
  function getList() {
    if (!listFn) return
    if (typeof listFn === 'function') {
      listFn()
    } else {
      loading.value = true
      request
        .get(listFn, searchForm.value)
        .then(res => {
          listData.value = res?.list || []
          total.value = res?.total || 0
        })
        .finally(() => {
          loading.value = false
        })
    }
  }

  // 搜索方法，可根据需要自行传参覆盖
  function search() {
    if (searchFn && typeof searchFn === 'function') {
      searchFn()
    } else {
      searchForm.value.pageNum = 1
      getList()
    }
  }

  // 表格选中数据
  const selections = ref([]) // 选中列表
  function handleSelection(selection: any) {
    selections.value = []
    if (!selection || typeof selection !== 'object') return
    if (Array.isArray(selection)) {
      selections.value = selection // 多选
    } else {
      selections.value = [selection] // 单选
    }
  }

  // 字段排序
  function handleSort(row: any) {
    if ((row?.column?.sortable || '') !== 'custom') return
    const { prop, order } = row
    if (order && prop) {
      searchForm.value.orderByColumn = prop || ''
      searchForm.value.orderBySort = order || ''
    } else {
      searchForm.value.orderByColumn = ''
      searchForm.value.orderBySort = ''
    }
    search()
  }

  // 默认添加和修改表单，方法可以根据需要自定义不使用该方法
  const formData = ref(null)
  const formShow = ref(false)
  function handleAdd() {
    formData.value = null
    formShow.value = true
  }
  function handleEdit(row: any) {
    let formId = undefined
    if (Array.isArray(row)) {
      formId = row.length && idField.value in row[0] ? row[0][idField.value] : undefined
    } else {
      formId = row?.id || selections.value[0]?.id || undefined
    }
    if (!formId) return msgWarning('参数缺失')
    formData.value = { id: formId }
    formShow.value = true
  }

  // 删除操作
  function handleDelete(row: any, extend = {}) {
    let rows = []
    if (!Array.isArray(row) && !(idField.value in row)) {
      rows = parseRows(selections.value, false, idField.value)
    } else {
      rows = parseRows(row, false, idField.value)
    }
    if (!rows.length) return msgWarning('未选择数据')
    let params = { [idField.value]: rows.map(item => item[idField.value]).join(','), ...extend }

    confirm(deleteTitle(rows))
      .then(() => {
        if (!deleteFn) return
        if (typeof deleteFn === 'function') {
          deleteFn(params)
        } else {
          request.post(deleteFn, params).then(res => {
            msgSuccess(res?.msg || '删除成功')
            getList()
          })
        }
      })
      .catch(() => {})
  }

  // 获取删除确认提示语
  function deleteTitle(rows: Array<any>) {
    let ids = rows.map(item => item[idField.value])
    let title = '确认 "删除" ' + moduleName.value + ' 编号为 "' + ids.join(',') + '" 的数据项？'
    if (rows.length === 1 && nameField.value && nameField.value in rows[0]) {
      title = '确认 "删除" ' + moduleName.value + ' "' + rows[0][nameField.value] + '" ？'
    }
    return title
  }

  // 树形表格展开收起
  const isExpandAll = ref(true) // 默认全部展开
  const refreshTable = ref(true) // 重新渲染表格状态
  function handleExpand() {
    refreshTable.value = false
    isExpandAll.value = !isExpandAll.value
    nextTick(() => (refreshTable.value = true))
  }

  // 导出
  function handleExport() {
    if (!exportFn) return
    if (typeof exportFn === 'function') {
      exportFn()
    } else {
      request.download(exportFn, searchForm.value)
    }
  }

  // 刷新缓存
  function handleCache() {
    if (!cacheFn) return
    if (typeof cacheFn === 'function') {
      cacheFn()
    } else {
      request.post(cacheFn).then(() => {
        msgSuccess('刷新缓存成功')
      })
    }
  }

  return {
    idField,
    nameField,
    moduleName,
    loading,
    total,
    listData,
    getList,
    searchForm,
    search,
    selections,
    handleSelection,
    handleSort,
    formData,
    formShow,
    handleAdd,
    handleEdit,
    handleDelete,
    deleteTitle,
    isExpandAll,
    refreshTable,
    handleExpand,
    handleExport,
    handleCache
  }
}
